package com.xsqf.jt808.netty.handler;

import com.xsqf.jt808.common.config.ChannelManager;
import com.xsqf.jt808.common.vo.DataPacket;
import com.xsqf.jt808.common.vo.req.terminal.AuthMsg;
import com.xsqf.jt808.common.vo.resp.CommonResp;
import com.xsqf.jt808.entity.VehicleRegisterInfo;
import com.xsqf.jt808.service.IVehicleRegisterInfoService;
import com.xsqf.jt808.common.vo.resp.RegisterResp;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author:
 * @Date: 2020-5-14
 * @Description: 鉴权消息->CommonResp
 * @Version: 1.0
 */

@Slf4j
@Component
@ChannelHandler.Sharable
public class AuthMsgHandler extends BaseHandler<AuthMsg> {

    @Autowired
    private ChannelManager channelManager;
    //    @Autowired
//    RegisterInfoDao registerInfoDao;
    @Autowired
    IVehicleRegisterInfoService registerInfoService;


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, AuthMsg msg) {
        log.info("鉴权：" + msg.toString());
        channelManager.add(msg.getHeader().getTerminalPhone(), ctx.channel());
        CommonResp resp = authResp(msg, getSerialNumber(ctx.channel()));
        write(ctx, resp);
    }

    /**
     * 终端鉴权
     */
    public CommonResp authResp(AuthMsg msg, short flowId) {
        DataPacket.Header header = msg.getHeader();
        CommonResp resp = new CommonResp();
        resp.getHeader().setTerminalPhone(msg.getHeader().getTerminalPhone());
        resp.getHeader().setFlowId(flowId);
        resp.setReplyFlowId(msg.getHeader().getFlowId());
        resp.setReplyId(msg.getHeader().getMsgId());
        resp.setResult(CommonResp.FAILURE);

        //查询终端注册信息并鉴权
        VehicleRegisterInfo registerInfo = registerInfoService.findByTerminalId(header.getTerminalPhone());
        if (registerInfo != null) {
            if (msg.getAuthCode().equals(registerInfo.getAuthCode())) {
                String key = "KEY:" + msg.getHeader().getTerminalPhone();
                redisTemplate.opsForHash().put(key, "isAuthenticated", true);
                resp.setResult(RegisterResp.SUCCESS);
            }
        }
        return resp;
    }
}
